#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
@__author:xiaojungao(借鉴luruiyaun)
'''
import os
from  email.mime.text import MIMEText
from  email.mime.multipart import MIMEMultipart
from email.header import Header
import smtplib

class GetNewReportAndSendMail(object):
    def __get_new_report(self):
        result_dir = './reports'
        lists = os.listdir(result_dir)
        lists.sort(key=lambda fn: os.path.getmtime(result_dir + '\\' + fn))
        print("最新文件为：" + lists[-1])
        new_report_file = os.path.join(result_dir, lists[-1])
        print("new_report_file==?",new_report_file)
        return new_report_file
    def __report_content(self):
        with open(self.__get_new_report(), 'rb') as f:
            file_content = f.read()
            print("file_content===?",file_content)
        return file_content

    def __send_mail(self,smtpserver,sender,psw,receiver,):
        u'''发送最新测试报告内容'''
        # 定义邮件内容
        self.smtpserver=smtpserver
        self.sender=sender
        self.psw=psw
        self.receiver=receiver
        msg = MIMEMultipart()
        mail_tital="""<div>
                         <p>您好！！</p>
                         <p>Python 邮件发送测试...可不必理会可不必理会</p>
                         <p>谢谢！！</p>
                    </div></br>
                """
        mail_body= self.__report_content()
        msg.attach(MIMEText(mail_tital,'html','utf-8'))
        msg.attach(MIMEText(mail_body,'html','utf-8'))
        Subject=u'自动化测试报告'
        msg['Subject']=Header(Subject,'utf-8')
        msg['from'] = self.sender
        msg['psw'] = self.psw
        msg['receiver'] = ";".join(receiver)

        # 添加附件
        att1 =MIMEText(open(self.__get_new_report(),'rb').read(),'base64','utf-8')
        att1['Content-Type']='application/octet-stream'
        att1['Content-Disposition']='attachment;filename="report.html"'
        msg.attach(att1)
        # 登录邮箱
        try:
            smtp =smtplib.SMTP()
            smtp.connect(self.smtpserver)
            # 用户名密码
            smtp.login(self.sender,self.psw)
            # smtp.sendmail(sender,receiver,msg.as_string())
            smtp.sendmail(self.sender,self.receiver,msg.as_string())
            smtp.quit()
            print('test report emial has send out!')
        except Exception as e:
            print('mail send fial,',e)

    def sendMail(self):
        self.mtp_server = 'smtp.qq.com'
        self.sender = '1457252030@qq.com'
        self.pwd = 'wpaswqvmizxjficc'  # 发送邮件的授权码
        self.receivers = ['1457252030@qq.com',]
        self.__send_mail(self.mtp_server,self.sender,self.pwd,self.receivers)

if __name__ == '__main__':
    aa =GetNewReportAndSendMail()
    aa.sendMail()